package com.quotientintelligence.webdev.caftrak;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.*;

//import com.google.appengine.api.users.User;
//import com.google.appengine.api.users.UserService;
//import com.google.appengine.api.users.UserServiceFactory;

import javax.jdo.PersistenceManager;
import com.quotientintelligence.PMF;

import com.quotientintelligence.caftrak.shared.*;



@SuppressWarnings("serial")
public class ListReader extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		//UserService us = UserServiceFactory.getUserService();
		//User u = us.getCurrentUser();
		
		PrintWriter pr = resp.getWriter();
		PersistenceManager pm = PMF.get().getPersistenceManager();

		if (!req.getParameter("CleanHouse").isEmpty() && req.getParameter("CleanHouse").equals("ayup")){
			String query = "select from " + Drink.class.getName();
			@SuppressWarnings("unchecked")
			List<Drink> deletableDrinks = (List<Drink>) pm.newQuery(query).execute();
			if (!deletableDrinks.isEmpty()) 
				pm.deletePersistentAll(deletableDrinks);
			
		}else
		{
			CafLoader cl = new CafLoader();
			
			ArrayList<Drink> drinks = (ArrayList<Drink>) cl.read();
			
			for (Drink d:drinks) {
				pr.print(d.Name + " has: " );
				for (Substance s:d.getIngredients()){
					//if(s.get_substanceType().equals(ActiveIng.Caffeine)){
						pr.print(s.get_quantity() + " " + s.get_quantUnits() + "s of " 
								+ s.get_substanceType());
						pr.println(" in " + d.Volume + " ounces of beverage, a ratio of " 
								+ d.getIngredientRatio(s.get_substanceType()));
					//}
				}
				try
				{
					pm.makePersistent(d);
				}
				catch (Exception e)
				{
					pr.println(e.getMessage());
				}
			}
		}/*
		 * try
		{
		
		    String query = "select from " + ConsumptionEvent.class.getName();
		    @SuppressWarnings("unchecked")
			List<ConsumptionEvent> drinks = (List<ConsumptionEvent>) pm.newQuery(query).execute();
		    if (drinks.isEmpty()) {
		    	pr.println("<p>You have not consumed any drinks!</p>");
		    } else {
		        for (ConsumptionEvent d : drinks) {
		            if (d.getUser() == null) {
				    	pr.println("<p>An anonymous person chugged:</p>");
		            } else {
				    	pr.println("<p>" + d.getUser().getNickname() + " drank:</p>");
		            }
	
		            if(d.getSubstance() != null)
			            pr.println(
			            		"<blockquote>" + d.getSubstance().Name + " a " + 
			            		d.getSubstance().Name + " on " 
			            		+ d.getDate() + "</blockquote>");
		        }
		    }
		}
		finally
		{
			pm.close();
		}
*/
	}
}

